package com.cxh.rmsq.ui.fragment.self

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.annotation.Nullable
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cxh.rmsq.R
import com.cxh.rmsq.db.model.BaseResultListBean
import com.cxh.rmsq.db.model.CommunityContent
import com.cxh.rmsq.db.model.GroupEntity
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.model.Result2
import com.cxh.rmsq.net.RetrofitUtil
import com.cxh.rmsq.net.newNet.ProjectViewModel
import com.cxh.rmsq.ui.adapter.self.CircleListAdapter
import com.cxh.rmsq.ui.adapter.self.SelectHoriTypeListAdapter
import com.cxh.rmsq.ui.fragment.BaseFragment
import com.cxh.rmsq.ui.widget.CustomRecyclerView
import com.cxh.rmsq.utils.GlideEngine
import com.cxh.rmsq.utils.MyUtils
import com.cxh.rmsq.utils.ToastUtils
import com.cxh.rmsq.viewmodel.SocialCircleViewModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener
import com.lxj.xpopup.XPopup
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

/**
 * 圈子
 */
class CircleFragment : BaseFragment(), CircleListAdapter.OnCustomClickListener {

    private lateinit var refreshList: SmartRefreshLayout
    private lateinit var rvType: CustomRecyclerView
    private lateinit var recyclerView: RecyclerView

    private var listAdapter: CircleListAdapter? = null
    private var horiTypeAdapter: SelectHoriTypeListAdapter? = null
    private var page = 1
    private var socialCircleViewModel: SocialCircleViewModel? = null
    private val dataList: MutableList<CommunityContent> = ArrayList()
    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(ProjectViewModel::class.java)
    }
    var typeList: MutableList<GroupEntity>? = null

    var circleId = ""
    private val imagesMediaList = java.util.ArrayList<LocalMedia>()

    override fun getLayoutResId(): Int {
        return R.layout.fragment_circle
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        socialCircleViewModel = ViewModelProviders.of(this).get(
            SocialCircleViewModel::class.java
        )
        refreshList = view.findViewById(R.id.refresh_list) as SmartRefreshLayout
        recyclerView = view.findViewById(R.id.rv_list) as RecyclerView
        rvType = view.findViewById(R.id.rv_type)

        recyclerView.layoutManager = LinearLayoutManager(context)
        listAdapter = CircleListAdapter(3, this)
        listAdapter!!.setEmptyView(View.inflate(activity, R.layout.empty_data_layout, null))
        recyclerView.adapter = listAdapter
        listAdapter!!.setOnItemClickListener { adapter, view, position -> }
        listAdapter!!.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.iv_like -> {
                    var type = 0
                    type = if (listAdapter!!.data[position].isLiked == 1) { //已点赞
                        0
                    } else {
                        1
                    }
                    val paramsMap = HashMap<String, Any>()
                    paramsMap["busId"] = listAdapter!!.data[position].id
                    paramsMap["userId"] = IMManager.getInstance().currentId
                    paramsMap["type"] = 1 //1动态2评论
                    paramsMap["isLiked"] = type //1:点赞 0：取消
                    paramsMap["bdzUserId"] = listAdapter!!.data[position].userId //被点赞用户id,
                    val body = RetrofitUtil.createJsonRequest(paramsMap)
                    socialCircleViewModel!!.commentLiked(body)
                    val finalType = type
                    socialCircleViewModel!!.commentLiked()
                        .observe(requireActivity(), object : Observer<Result2<String>> {
                            override fun onChanged(result: Result2<String>) {
                                if (result.code == 200) {
//                                    if (finalType ==1){
//                                        ToastUtils.showToast("点赞成功");
//                                    }
                                    socialCircleViewModel!!.getCommunityPage(
                                        IMManager.getInstance().currentId,
                                        dataList[position].userId.toString() + "",
                                        page,
                                        10
                                    )
                                    //                                    dataList.set(position, newData.get(position));
                                }
                            }
                        })
                }
            }
        }

        refreshList.resetNoMoreData()
        refreshList.setRefreshHeader(MaterialHeader(activity))
        refreshList.setRefreshFooter(ClassicsFooter(activity))
        refreshList.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                socialCircleViewModel!!.getCircleCommunityPage(
                    IMManager.getInstance().currentId,
                    circleId,
                    page,
                    10
                )
                refreshLayout.finishLoadMore()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                dataList.clear()
                listAdapter!!.setNewInstance(null)
                socialCircleViewModel!!.getCircleCommunityPage(
                    IMManager.getInstance().currentId,
                    circleId,
                    page,
                    10
                )
            }
        })
    }

    @Nullable
    override fun onInitView(savedInstanceState: Bundle?, intent: Intent) {

    }

    override fun onResume() {
        super.onResume()
        viewModel.getCircleTypeList {
            if (it.data.size > 0) {
                typeList = it.data
                circleId = typeList!![0].id.toString()
                Log.e("circleIdddddd", circleId)
                page = 1
                dataList.clear()
                listAdapter!!.setNewInstance(null)
                socialCircleViewModel!!.getCircleCommunityPage(
                    IMManager.getInstance().currentId,
                    circleId,
                    page,
                    10
                )

                horiTypeAdapter = SelectHoriTypeListAdapter()
                rvType.layoutManager =
                    LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
                rvType.adapter = horiTypeAdapter
                horiTypeAdapter!!.setNewInstance(typeList)
//            horiTypeAdapter!!.setSelectPos(0)

                horiTypeAdapter!!.setOnItemClickListener { adapter, view, position ->
                    if (position != horiTypeAdapter!!.getSelectPos()) {
                        horiTypeAdapter!!.setSelectPos(position)
                        circleId = typeList!![position].id.toString()
                        Log.e("circleIdddddd", circleId)
                        horiTypeAdapter!!.notifyDataSetChanged()
                        socialCircleViewModel!!.getCircleCommunityPage(
                            IMManager.getInstance().currentId,
                            circleId,
                            page,
                            10
                        )
                    }
                }
            }
        }
        page = 1
        dataList.clear()
        listAdapter!!.setNewInstance(null)
        socialCircleViewModel!!.getCircleCommunityPage(
            IMManager.getInstance().currentId,
            circleId,
            page,
            10
        )
        socialCircleViewModel!!.circleCommunityPage.observe(
            this,
            object : Observer<Result2<BaseResultListBean>> {
                override fun onChanged(result: Result2<BaseResultListBean>) {
                    Log.e("total", result.data!!.total.toString() + "")
                    if (refreshList!!.isRefreshing) {
                        refreshList!!.finishRefresh()
                    }
                    if (result.data != null) {
                        if (page == 1) {
                            listAdapter!!.setNewInstance(result.data!!.list)
                            if (result.data.list!!.size < 10) {
                                refreshList.setEnableLoadMore(false)
                            } else {
                                refreshList.setEnableLoadMore(true)
                            }
                        } else {
                            if (result.data!!.list!!.size > 0) {
                                listAdapter!!.addData(result.data!!.list!!)
                                refreshList!!.setEnableLoadMore(true)
                            } else {
                                refreshList!!.setEnableLoadMore(false)
                                //                            listAdapter.getLoadMoreModule().loadMoreEnd(false);
//                            listAdapter.getLoadMoreModule().loadMoreComplete();
                                refreshList!!.finishLoadMoreWithNoMoreData()
                            }
                        }
                        dataList.addAll(result.data!!.list!!)
                        Log.e("datalist.size", dataList.size.toString() + "")
                        listAdapter!!.notifyDataSetChanged()
                    }
                }
            })
    }

    companion object {
        private const val ARG_PARAM1 = "param1"
        fun newInstance(param1: String?): CircleFragment {
            val fragment = CircleFragment()
            val args = Bundle()
            args.putString(ARG_PARAM1, param1)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onItemClick(position: Int, data: CommunityContent?) {

        var pos = 0
        imagesMediaList.clear()
        if (!TextUtils.isEmpty(data!!.files)) {
            if (data!!.files!!.contains(",")) { //多张
                for (i in MyUtils.toList(data!!.files).indices) {
                    val localMedia = LocalMedia()
                    localMedia.path = MyUtils.toList(data!!.files)[i]
                    imagesMediaList.add(localMedia)
                }
                pos = position
            } else {
                val localMedia = LocalMedia()
                localMedia.path = data!!.files
                imagesMediaList.add(localMedia)
                pos = 0
            }
        }
        PictureSelector.create(activity)
            .openPreview()
            .setImageEngine(GlideEngine.createGlideEngine())
            .isPreviewFullScreenMode(true)
//            .isPreviewZoomEffect(true, rlvCampClockImages)
            .setExternalPreviewEventListener(object : OnExternalPreviewEventListener {
                override fun onPreviewDelete(position: Int) {

                }

                override fun onLongPressDownload(
                    context: Context,
                    media: LocalMedia
                ): Boolean {
                    return true
                }
            })
            .startActivityPreview(pos, false, imagesMediaList)
    }

    override fun onGroupClick(position: Int, data: CommunityContent?) {

    }

    override fun onItemLongClick(position: Int, data: CommunityContent?) {
        XPopup.Builder(activity)
            .dismissOnTouchOutside(true)
            .dismissOnBackPressed(true)
            .asBottomList(
                "", arrayOf("下载")
            ) { position, text ->
                if (data!!.pictureDownload == 1) {
                    if (data!!.fileType == 1) { //图片
                        if (!TextUtils.isEmpty(data!!.files)) {
                            if (data!!.files!!.contains(",")) { //多张
                                MyUtils.downloadImage(
                                    activity,
                                    MyUtils.toList(data!!.files)[position]
                                )
                            } else {
                                MyUtils.downloadImage(activity, data!!.files)
                            }
                        }
                    } else {
                        MyUtils.downloadFromNetwork(activity, data!!.files)
                    }
                } else {
                    ToastUtils.showToast("不允许下载！")
                }
            }.show()
    }
}